package cool.taomu.web.utils

import cool.taomu.stock.StockApiPy
import cool.taomu.utils.ThriftUtils
import cool.taomu.utils.h2.H2Utils
import java.io.File
import java.util.List
import org.slf4j.LoggerFactory

class StockDataUtils {
	val LOG = LoggerFactory.getLogger(StockDataUtils);
	val sql = "create table if not exists stock_data(code varchar(10),name varchar(6),industry varchar(6),industryClassification varchar(6),updateDate varchar(10))";
	val h2 = new H2Utils();
	val static instance = new StockDataUtils;

	private new() {
		h2.modify(sql);
		var file = new File("./usecase/stock_code_data.csv");
		if (!file.exists) {
			//TODO 需要修改
			ThriftUtils.rpc("127.0.0.1", 8091, [
				var stock = new StockApiPy.Client(it);
				var data = stock.stockCodeData;
				data.forEach [
					var sql2 = "insert into stock_data(updateDate,code,name,industry,industryClassification) values(?,?,?,?,?)";
					h2.modify(sql2, it as List);
				]
			])
			LOG.info("生成文件");
			h2.modify("call csvwrite('" + file.absolutePath + "','select * from stock_data')");
		} else {
			LOG.info("从文件加载数据")
			h2.modify("insert into stock_data (select * from csvread('" + file.absolutePath + "'))");
		}
	}

	def static getInstance() {
		return instance;
	}

	def getH2() {
		return h2;
	}
}
